package com.csair.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.WindowManager;

import com.csair.common.AppUtilsConfig;
import com.csair.mbp.common.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public final class AppUtils {

//    public static void addAppShortcut(Context context, String shortCutName, int iconId) {
//        Intent intent = new Intent(Intent.ACTION_MAIN);
//        intent.setClassName(context, "com.csair.mbp.WelcomeActivity");
//
//        ShortcutIconResource iconRes = ShortcutIconResource.fromContext(context, iconId);
//
//        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortCutName);
//        shortcut.putExtra("duplicate", false);
//        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
//        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
//        context.sendBroadcast(shortcut);
//    }

    /**
     * ******************************************
     * ************** 清理App ****************
     */
    public static void cleanApplicationData(Context context, String... filepath) {
        cleanInternalCache(context);
        cleanDatabases(context);
        cleanSharedPreference(context);
        cleanFiles(context);
        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }
    }
    private static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }
    private static void cleanDatabases(Context context) {
        deleteFilesByDirectory(new File(context.getFilesDir().getPath()
                + context.getPackageName() + "/databases"));
    }
    public static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }
    private static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }
    private static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }
    private static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File(context.getFilesDir().getPath()
                + context.getPackageName() + "/shared_prefs"));
    }
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    /******************************************/
    /******************************************/

    /**
     * 获取App版本
     */
    public static String getAppVersion(Context context) {
        PackageManager manager = context.getPackageManager();
        String packageName = context.getPackageName();
        try {
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            return info.versionName + "." + info.versionCode;
        } catch (NameNotFoundException e) {
            LogUtils.printStackTrace(e);
        }
        return "";
    }

    /**
     * **************** 第一次启动App ******************
     */
    public static boolean isFirstBoot(Context context) {
        return SharedPreferencesUtil.getInstance(AppUtilsConfig.PREFERENCE_APPCONFIG_FILENAME).getBoolean(context.getString(R.string.common_EXTRA_0001,getAppVersion(context)),true);
    }
    public static void setIsFirstBoot(Context context, boolean isFirstBoot) {
        SharedPreferencesUtil.getInstance(AppUtilsConfig.PREFERENCE_APPCONFIG_FILENAME).saveBoolean(context.getString(R.string.common_EXTRA_0001,getAppVersion(context)),isFirstBoot);
    }
    /******************************************/


    /**
     * ****************** 安装应用 ******************
     */
    public static void installApk(Context context, String filePath) {
        File file = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.csair.mbp", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 对于安卓4.4以上、5.0以下系统实现状态栏沉浸式显示
     */
    public static void setTranlucentStatus(Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

    /**
     * 判断当前Activity是否在前台显示
     */
    public static boolean isForeground(Activity activity,String className) {
        if (activity.getApplicationContext() == null || TextUtils.isEmpty(className)) return false;
        ActivityManager am = (ActivityManager) activity.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) return true;
        }
        return false;
    }

    /**
     * 判断当前应用是否处于前台
     */
    public static boolean isAppForeground(Context context) {
        if (context != null) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
                if (processInfo.processName.equals(context.getPackageName())) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 根据报名判断某APP是否安装
     *
     * @param packageName 目标APP包名
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }

    /**
     * 返回指定的 Activity
     */
    public static void backToActivity(Activity activity, Class<?> targetActivity) {
        Intent intent = new Intent(activity, targetActivity);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        activity.startActivity(intent);
    }

    /**
     * 重启应用
     */
    public static void restartApplication(Context context) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
        Process.killProcess(Process.myPid());
    }

    /**
     * 结束应用程序
     */
    public static void finishApplication(Activity activity) {
        ActivityManager var1 = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= 21) {
            List var2 = var1.getAppTasks();

            for (Object aVar2 : var2) {
                ActivityManager.AppTask var3 = (ActivityManager.AppTask) aVar2;
                String pn1 = var3.getTaskInfo().baseIntent.getComponent().getPackageName();
                if (pn1.equals(activity.getPackageName())) var3.finishAndRemoveTask();
            }
        }

        var1.killBackgroundProcesses(activity.getPackageName());
        Process.killProcess(Process.myPid());
    }
}
